package com.heima.account.action;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.heima.account.entity.Account;
import com.heima.account.entity.AccountFreeze;
import com.heima.account.service.IAccountFreezeService;
import com.heima.account.service.IAccountService;
import io.seata.core.context.RootContext;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AccountActionImpl implements AccountAction {
    @Autowired
    private IAccountService accountService;
    @Autowired
    private IAccountFreezeService iAccountFreezeService;
    @Override
    //我不想努力了，写下伪代码吧，感觉解决空回滚的时候，
    //因为cancel先进来，有责任先创建一个冻结表，设置一个状态标记
    //这样try进来通过Xid搜索有表，然后通过状态也知道cancel了，
    //直接return可以防止业务悬挂。。
    //代码写起来就算了，能动就行
    public void deduct(Integer userId, Integer money) {
        String xid = RootContext.getXID();
//        AccountFreeze byId = iAccountFreezeService.getById(xid);
        //如果这个id的冻结表已经有了，并且状态为cancel，就直接return
        //abababa
        AccountFreeze accountFreeze = new AccountFreeze();
        accountFreeze.setXid(xid);
        accountFreeze.setFreezeMoney(money);
        accountFreeze.setUserId(userId);
        iAccountFreezeService.save(accountFreeze);
        LambdaUpdateWrapper<Account> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Account::getUserId,userId).setSql("money=money -"+money);
        accountService.update(updateWrapper);
    }

    @Override
    public boolean confirm(BusinessActionContext context) {

        String xid = context.getXid();
        iAccountFreezeService.removeById(xid);
        return true;
    }

    @Override
    public boolean cancel(BusinessActionContext context) {
        String xid = context.getXid();
        AccountFreeze accountFreeze = iAccountFreezeService.getById(xid);
        //如果没有，则创建表设置状态为cancel，再return
        if(accountFreeze!=null)
        {
            LambdaUpdateWrapper<Account> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Account::getUserId,accountFreeze.getUserId());
            updateWrapper.setSql("money = money +"+accountFreeze.getFreezeMoney());
            accountService.update(updateWrapper);
            iAccountFreezeService.removeById(xid);
        }
        else
        {
            System.out.println("伪代码哈哈哈这里创建一个新冻结表设置标记为cancel，然后return以防业务悬挂");
        }
        return true;

    }
}
